// pages/mine/mine.js
const db = wx.cloud.database().collection('user');
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {},
  aboutus: function (res) {
    wx.navigateTo({
      url: '../aboutus/aboutus',
    })
  },
  bindlogin: function (res) {
    wx.navigateTo({
      url: '../login/login',
    })
  },
  scan: function (res) {
    wx.navigateTo({
      url: '../scan/scan',
    })
  },
  active: function (res) {
    wx.showToast({
      title: '最近没有活动',
      icon: 'none',
      duration: 1000,
    })
  },
  coll: function (res) {
    wx.navigateTo({
      url: '../collection/collection',
    })
  },
  bwr: function (res) {
    wx.navigateTo({
      url: '../bwrecords/bwrecords',
    })
  },

  bkm: function (res) {
    wx.navigateTo({
      url: '../bookmanager/bookmanager',
    })
  },

  bwm: function (res) {
    wx.navigateTo({
      url: '../bwmanager/bwmanager',
    })
  },

  userm: function (res) {
    wx.navigateTo({
      url: '../usermanager/usermanager',
    })
  },

  onGetOpenid: function () {
    // 调用云函数
    wx.cloud.callFunction({
      name: 'login',
      data: {},
      success: res => {
        console.log('[云函数] [login] user openid: ', res.result.openid)
        app.globalData.openid = res.result.openid
        this.username(res)
      },
      fail: err => {
        console.error('[云函数] [login] 调用失败', err)
      }
    })
  },

  onGetUserInfo: function (e) {
    if (!this.data.logged && e.detail.userInfo) {
      this.onGetOpenid()
      this.setData({
        logged: true,
        userInfo: e.detail.userInfo,
      })
    }
    app.globalData.userInfo = e.detail.userInfo
    this.isexist()
  },

  isexist: function () {
    const db = wx.cloud.database()
    db.collection("book_user")
      .where({
        _openid: getApp().globalData.openid
      })
      .get().then(res => {
        const userLen = res.data.length;
        if (userLen === 0) {
          // 获取当前时间
          var timestamp = Date.parse(new Date());
          timestamp = timestamp / 1000;
          var n = timestamp * 1000;
          var date = new Date(n);
          console.log(date.toLocaleDateString());
          const db = wx.cloud.database()
          db.collection("book_user")
            .add({
              data: {
                imgPath: getApp().globalData.userInfo.avatarUrl,
                rgdate: date.toDateString(),
                booksum:0
              },
            })
          wx.navigateTo({
            url: '../userinfo/userinfo',
          })
        }
      })
  },

  settle: function (e) {
    if (!this.data.logged && e.detail.userInfo) {
      this.onGetOpenid()
      this.setData({
        logged: true,
        userInfo: e.detail.userInfo,
      })
    } else if (this.data.logged) {
      wx.navigateTo({
        url: '../userinfo/userinfo',
      })
    }
    app.globalData.userInfo = e.detail.userInfo
    this.isexist()
  },


  /**
   * 生命周期函数--监听页面加载
   */

//获取用户名
  username: function (res) {    
    const db = wx.cloud.database()
    db.collection("book_user")
      .where({
        _openid: res.result.openid
      })
      .get({
        success: res => {
            this.setData({
              userlevel: res.data[0].booksum,
              username: res.data[0].name,
              role:res.data[0].role,
            })
            console.log('11111',this.data)
        },
        fail: err => {
          console.log(err)
        }
      })
  },


  onLoad: function (options) {

    this.onGetOpenid()
    //获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              this.setData({
                userInfo: res.userInfo,
                logged: true,
              })
              app.globalData.userInfo = res.userInfo,
                console.log(this.data.userInfo)
            }
          })
        }
      }
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.showNavigationBarLoading()
    this.onLoad()
    setTimeout(() => {
      wx.hideNavigationBarLoading()
      wx.stopPullDownRefresh()
    }, 2000);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})